package com.tzx.fluttermixedapplication.net

import com.tzx.base.utils.AppHelper
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

enum class RepositoryFactory(private val baseUrl: String) {
    OIO(OIO_BASE_URL),
    VVH(VVH_BASE_URL);


    private val mCache: Cache by lazy {
        Cache(File(AppHelper.application.cacheDir, "app_cache"), (10 * 1024 * 1024).toLong())
    }

    private val client: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .addInterceptor {
                val response = it.proceed(it.request())
                val body = response.body
                val contentType = body?.contentType()
                // val string = body?.string()?.replace("200", "-1")
                val string = body?.string()
                println(string)
                val create = ResponseBody.create(contentType, string ?: "")
                response.newBuilder().body(create).build()
            }
            .connectTimeout(8, TimeUnit.SECONDS)
            .cache(mCache)
            .build()
    }

    private val mRetrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    fun <T> createApiService(cls : Class<T>): T {
        return mRetrofit.create(cls)
    }
}